<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="搜索内容" prop="searchContent">
        <el-input
          v-model="queryParams.searchContent"
          placeholder="请输入描述或映射字段或属性名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select
          v-model="queryParams.equipmentType"
          placeholder="设备类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in this.equipmentTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleCopyAdd"
        >复制新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <!-- 自增序号列 -->
      <el-table-column type="index" label="序号">
        <!-- 自定义索引 (可选) -->
        <template slot-scope="scope">
          {{ serial_number + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" key="equipmentType" prop="equipmentType" v-if="columns[1].visible"
                       width="120"/>
      <el-table-column label="描述" align="center" key="description" prop="description" v-if="columns[2].visible" width="200"/>
      <el-table-column label="可选值" align="center" key="type" prop="type" v-if="columns[3].visible"/>
      <el-table-column label="映射字段" align="center" key="mapField" prop="mapField" v-if="columns[4].visible" width="200"/>
      <el-table-column label="标准单位" align="center" key="standardUnit" prop="standardUnit" v-if="columns[5].visible"
                       width="120"/>
      <el-table-column label="属性名" align="center" key="propertyName" prop="propertyName" v-if="columns[6].visible"
                       width="200"/>
      <el-table-column label="全称属性名" align="center" key="fullPropertyName" prop="fullPropertyName"
                       v-if="columns[7].visible" width="120"/>
      <el-table-column label="备注" align="center" key="remark" prop="remark" v-if="columns[8].visible" width="120"/>
      <el-table-column label="返回类型" align="center" key="resultType" prop="resultType" v-if="columns[9].visible"
                       width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[10].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.id !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentType">
              <el-select
                v-model="form.equipmentType"
                placeholder="设备类型"
                clearable
                style="width: 190px">
                <el-option
                  v-for="dict in this.equipmentTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" placeholder="请输入描述" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可选值" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入可选值" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="映射字段" prop="mapField">
              <el-input v-model="form.mapField" placeholder="请输入映射字段" type="text" maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="属性名">
              <el-input v-model="form.description" type="text" placeholder="请输入属性名"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="全称属性名">
              <el-input v-model="form.fullDescription" type="text" placeholder="请输入全称属性名"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="text" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="返回类型">
              <el-input v-model="form.returnType" type="text" placeholder="请输入返回类型"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPointStandardField,
  getPointStandardField,
  addPointStandardField,
  updatePointStandardField,
  delPointStandardField, batchDelPointStandardField
} from "@/api/system/basics/standard";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getEquipmentDictList} from "@/api/system/dict";

export default {
  name: "Standard",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: [],
      equipmentTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/point-standard/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchContent: '',
        equipmentType: ''
      },
      // 列信息
      columns: [
        {key: 0, label: `编号`, visible: true},
        {key: 1, label: `设备类型`, visible: true},
        {key: 2, label: `描述`, visible: true},
        {key: 3, label: `可选值`, visible: true},
        {key: 4, label: `映射字段`, visible: true},
        {key: 5, label: `标准单位`, visible: true},
        {key: 6, label: `属性名`, visible: true},
        {key: 7, label: `全称属性名`, visible: true},
        {key: 8, label: `备注`, visible: true},
        {key: 9, label: `返回类型`, visible: true},
        {key: 10, label: `创建时间`, visible: true}
      ],
      // 表单校验
      rules: {
        equipmentType: [
          {required: true, message: "设备类型不能为空", trigger: "blur"}
        ],
        description: [
          {required: true, message: "厂商描述不能为空", trigger: "blur"}
        ],
        standardDescription: [
          {required: true, message: "标准描述不能为空", trigger: "blur"}
        ],
        propertyName: [
          {required: true, message: "属性名不能为空", trigger: "blur"}
        ]
      }
    };
  },
  computed: {
    serial_number() {
      return this.queryParams.pageSize * (this.queryParams.pageNum - 1);
    }
  },
  created() {
    this.getEquipmentList();
    this.getList();
    this.loading = false;
  },
  methods: {
    getEquipmentList() {
      getEquipmentDictList().then(response => {
        let rows = response.data;
        this.equipmentTypeList = rows.map(style => ({
          value: style.id,
          label: style.name,
        }));
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listPointStandardField(this.queryParams).then(response => {
          this.dataList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id :undefined,
        online_enable: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加标准字段";
    },
    handleCopyAdd() {
      const ids = this.ids;
      if (ids.length > 1){
        this.$modal.msgWarning("只能选择一条数据");
        return;
      }
      const id = ids[0];
      // this.disabled = false;
      this.reset();
      getPointStandardField(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改标准字段";
        this.form.id = undefined;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getPointStandardField(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改标准字段";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePointStandardField(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPointStandardField(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除编号为"' + id + '"的数据项？').then(function () {
        return delPointStandardField(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleBatchDelete(row) {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return batchDelPointStandardField(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/point/export', {
        ...this.queryParams
      }, `point_tool_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/point-standard/importTemplate', {}, `point_tool_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
